package hrms.util.amq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;


/**
 * 点对点生产模式
 * @author Aikes
 *
 */
public class Producter {

    //ActiveMq 的默认用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //ActiveMq 的默认登录密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //ActiveMQ 的链接地址
    private static final String BROKEN_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    //链接工厂
    ConnectionFactory connectionFactory;
    //链接对象
    Connection connection;
    //事务管理
    Session session;
    
    ThreadLocal<MessageProducer> threadLocal;

    private static Producter producter = null;
    
    private Producter() {
    	init();
    }
    
    public static synchronized Producter getInstance() {
    	
    	if(producter == null) {
    		producter = new Producter();
    	}
    	return producter;
    	
    }
    
    public void init(){
        try {
        	threadLocal = new ThreadLocal<MessageProducer>();
            //创建一个链接工厂
            connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
            //从工厂中创建一个链接
            connection  = connectionFactory.createConnection();
            //开启链接
            connection.start();
            //创建一个事务（这里通过参数可以设置事务的级别）
            session = connection.createSession(true,Session.SESSION_TRANSACTED);
        } catch (JMSException e) {
            e.printStackTrace();
            System.out.println("init faild~");
        }
    }

    public boolean sendMessage(String disname , String mes){
        try {
            //创建一个消息队列
            javax.jms.Queue queue = session.createQueue(disname);
            //消息生产者
            MessageProducer messageProducer = null;
            if(threadLocal.get()!=null){
                messageProducer = threadLocal.get();
            }else{
                messageProducer = session.createProducer((Destination) queue);
                threadLocal.set(messageProducer);
            }
            //创建一条消息
            TextMessage msg = session.createTextMessage(mes);
            //发送消息
            messageProducer.send(msg);
            //提交事务
            session.commit();
        } catch (JMSException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}